import { defineStore } from "pinia";
import { ref, computed } from "vue";
import * as userApi from "@/api/user.js";
import { wxLogin } from "@/utils/wx";
import { DEFAULT_AVATAR } from "@/dict/user";
import { getToken, removeToken, setToken } from "@/utils/token";
/**
 * user仓库
 */
export const useUserStore = defineStore(
  "userStore",
  () => {
    // 默认头像
    const defaultAvatar = DEFAULT_AVATAR;
    //  用户信息
    const userInfo = ref(undefined);
    // 设置用户信息
    const setUserInfo = (obj) => {
      userInfo.value = {
        ...userInfo.value,
        ...obj,
      };
    };
    // 是否登录
    const isLogin = computed(() => {
      return !!userInfo.value?.id;
    });

    // 用code去换登录态-用户token
    const loginWithCode = async () => {
      return new Promise(async (resolve, reject) => {
        try {
          const token = getToken();
          if (token) return resolve(token);
          const code = await wxLogin();
          const { data } = await userApi.code2AccessToken({
            code: code,
          });
          setToken(data.token);
          resolve(data.token);
        } catch (error) {
          reject(error);
        }
      });
    };

    //   刷新用户信息
    const refreshUserInfo = async () => {
      const { data } = await userApi.getUserInfo();
      setUserInfo(data);
      return data;
    };

    // 设置用户信息
    const updateUserInfo = async (params) => {
      await userApi.updateUserInfo(params);
      return refreshUserInfo();
    };

    //   登录
    const login = async () => {
      await loginWithCode();
      await refreshUserInfo();
      return Promise.resolve();
    };
    //   登出
    const logout = async () => {
      userInfo.value = undefined;
      removeToken();
    };
    //   重新登录
    const reLogin = async () => {
      logout();
      login();
    };

    return {
      userInfo,
      refreshUserInfo,
      updateUserInfo,
      loginWithCode,
      isLogin,
      login,
      logout,
      reLogin,
      setUserInfo,
      defaultAvatar,
    };
  },
  {
    // 开启后对 state 的数据读写都将持久化
    unistorage: true,
  }
);
